package com.fishing.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import org.springframework.util.StringUtils;


public class DateUtil {
    
	public static String dateAdd(String dateStr,int day)throws ParseException{ //ParseException 解析异常 只能对日操作
		SimpleDateFormat sdf = new SimpleDateFormat();  //SimpleDateFormat中的parse方法可以 ,把String型的字符串转换成特定格式的date类型  
		Date date = sdf.parse(dateStr);  //parse()返回的是一个Date类型数据，format返回的是一个StringBuffer类型的数据
		Calendar c1 = Calendar.getInstance();  //Calendar操作日期
		c1.setTime(date);  //方法设置日历的时间为给定的日期   https://www.yiibai.com/java/util/calendar_settime.html
		c1.add(Calendar.DATE, day);  //https://www.yiibai.com/java/util/calendar_add.html
		date = c1.getTime();
		return sdf.format(date); //format返回的是一个StringBuffer类型的数据    https://blog.csdn.net/xuhengpan/article/details/78217555
	}
	
	/**
     * 获取过去第几天的日期
     *
     * @param past
     * @return
     */
	public static String getPastDate(int past) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.DAY_OF_YEAR, calendar.get(Calendar.DAY_OF_YEAR) - past);
        Date today = calendar.getTime();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String result = format.format(today);
        return result;
    }
	
	/***
	 * 获取时间区间的所有月份
	 * @param minDate
	 * @param maxDate
	 * @return
	 * @throws ParseException
	 */
	public static List<String> getMonthBetween(String minDate,String maxDate)throws ParseException{
		ArrayList<String> result = new ArrayList<String>();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");//格式化为年月
		if(StringUtils.isEmpty(minDate) && StringUtils.isEmpty(maxDate)) {  //StringUtils.isEmpty https://www.cnblogs.com/yaya-yaya/p/6096539.html
			result.add(sdf.format(new Date()));
			return result;
		}
		Calendar min = Calendar.getInstance();
		Calendar max = Calendar.getInstance();
		
		min.setTime(sdf.parse(minDate));
		min.set(min.get(Calendar.YEAR), min.get(Calendar.MONTH), 1);
		
		max.setTime(sdf.parse(maxDate));
	    max.set(max.get(Calendar.YEAR), max.get(Calendar.MONTH), 2);

	    Calendar curr = min;
	    while (curr.before(max)) {
	       result.add(sdf.format(curr.getTime()));
	       curr.add(Calendar.MONTH, 1);
	    }
	    return result;
	}
	
	/**
     * 日期格式字符串转换成时间戳
     *
     * @param dateStr 字符串日期
     * @param format   如：yyyy-MM-dd HH:mm:ss
     *
     * @return
     */
	public static Long Date2TimeStamp(String dateStr, String format) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat(format);
            return sdf.parse(dateStr).getTime() / 1000;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
	
	public static Map<String,Object> getOneDayTimeStamp(String dateStr, Map<String,Object> map) { //得到一天的时间戳
    	if(StringUtils.isEmpty(dateStr)){
    		return map;
    	}
    	String format = "yyyy-MM-dd HH:mm:ss";
        try {
            SimpleDateFormat sdf = new SimpleDateFormat(format);
            map.put("stime", sdf.parse(dateStr+" 00:00:00").getTime() / 1000) ;
            map.put("etime", sdf.parse(dateStr+" 23:59:59").getTime() / 1000) ;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }
	
	/**
     * Java将Unix时间戳转换成指定格式日期字符串
     * @param timestampString 时间戳 如："1473048265";
     * @param formats 要格式化的格式 默认："yyyy-MM-dd HH:mm:ss";
     *
     * @return 返回结果 如："2016-09-05 16:06:42";
     */
	public static String TimeStamp2Date(String timestampString, String formats) {  //可以输入自己想要的格式
		if(StringUtils.isEmpty(formats))
			formats = "yyyy-MM-dd HH:mm:ss";
			Long timestamp = Long.parseLong(timestampString) * 1000;
			String date = new SimpleDateFormat(formats, Locale.CHINA).format(new Date(timestamp));
	        return date;
	}
	
	public static String TimeStamp2Date(String timestampString) { //默认格式
        String formats = "yyyy-MM-dd HH:mm:ss";
        Long timestamp = Long.parseLong(timestampString) * 1000;
        String date = new SimpleDateFormat(formats, Locale.CHINA).format(new Date(timestamp));
        return date;
    }
	
	/***
	   * 取得当前的时间戳
	 * @return
	 * */
	public static String getNowTimeStamp() {
		long time = System.currentTimeMillis();  // http://blog.sina.com.cn/s/blog_6b8bd9d80101fe8t.html
		String nowTimeStamp = String.valueOf(time / 1000);  // 1s = 1000ms
		return nowTimeStamp;
	}
	
	public static Map<String,Object> getInitQueryMap(String stime, String etime, Map<String,Object> map) throws Exception {
    	if(!StringUtils.isEmpty(stime) && !StringUtils.isEmpty(etime) && stime.equals(etime)){
    		map.put("stime", Date2TimeStamp(stime + " 00:00:00", "yyyy-MM-dd HH:mm:ss"));
    		map.put("etime", Date2TimeStamp(etime + " 23:59:59", "yyyy-MM-dd HH:mm:ss"));
    	}else{
    		if(StringUtils.isEmpty(stime)){
        		map.put("stime", Date2TimeStamp(new SimpleDateFormat("yyyy-MM-dd").format(new Date()) + " 00:00:00", "yyyy-MM-dd HH:mm:ss"));
        	}else{
        		map.put("stime", Date2TimeStamp(stime + " 00:00:00", "yyyy-MM-dd HH:mm:ss"));
        	}
        	
        	if(StringUtils.isEmpty(etime)){
        		map.put("etime", Date2TimeStamp(new SimpleDateFormat("yyyy-MM-dd").format(new Date()) + " 23:59:59", "yyyy-MM-dd HH:mm:ss"));
        	}else{
        		map.put("etime", Date2TimeStamp(etime + " 23:59:59", "yyyy-MM-dd HH:mm:ss"));
        	}
    	}
    	return map;
    }
	
	/***
	 *根据开始时间和结束时间返回时间段内的时间集合
	 *@param beginDate
	 *@param endDate
	 *@return List
	 * */
	public static List<String> getDatesBetweenTwoDateStr(String beginDateStr, String endDateStr) throws Exception{ 
    	List<String> lDate = new ArrayList<String>();  
    	System.out.println("beginDateStr:"+beginDateStr);
    	System.out.println("endDateStr:"+endDateStr);
        if(beginDateStr.equals(endDateStr)){
        	lDate.add(beginDateStr);
        	return lDate;
        }
    	
    	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");  
    	Date beginDate = sdf.parse(beginDateStr);
    	Date endDate = sdf.parse(endDateStr);
    	
        
        lDate.add(beginDateStr);// 把开始时间加入集合  
        Calendar cal = Calendar.getInstance();  
        // 使用给定的 Date 设置此 Calendar 的时间  
        cal.setTime(beginDate);  
        boolean bContinue = true;  
        while (bContinue) {  
            // 根据日历的规则，为给定的日历字段添加或减去指定的时间量  
            cal.add(Calendar.DAY_OF_MONTH, 1);  
            // 测试此日期是否在指定日期之后  
            if (endDate.after(cal.getTime())) {  
                lDate.add(sdf.format(cal.getTime()));  
            } else {  
                break;  
            }  
        }  
        lDate.add(endDateStr);// 把结束时间加入集合  
        return lDate;  
    }  
    
    public static String fillZero(Integer num){
    	if(num > 9){
    		return String.valueOf(num);
    	}
    	return "0"+num;
    }
    /** 
     * 获取最近n个月，经常用于统计图表的X轴 
     */  
    public static String[] getLastnMonths(int n){  
        String[] lastnMonths = new String[n];  
          
        Calendar cal = Calendar.getInstance();  
        cal.set(Calendar.MONTH, cal.get(Calendar.MONTH)+1); //要先+1,才能把本月的算进去</span>  
        for(int i=0; i<n; i++){  
            cal.set(Calendar.MONTH, cal.get(Calendar.MONTH)-1); //逐次往前推1个月  
            lastnMonths[n-i-1] = cal.get(Calendar.YEAR)+ "-" + fillZero((cal.get(Calendar.MONTH)+1));  
        }  
        return lastnMonths;  
    } 
    
    /**
     * 获取过去几天的日期,包含当天
     *
     * @param past
     * @return
     */
    public static String [] getPastDates(int past) {
    	String [] days = new String[past];
    	
    	SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        
    	int index = 0;
        past = past - 1;
        for (int i = past; i >= 0; i--) {
        	Calendar calendar = Calendar.getInstance();
        	calendar.set(Calendar.DAY_OF_YEAR, calendar.get(Calendar.DAY_OF_YEAR) - i);
        	days[index] = format.format(calendar.getTime());
            index ++;
		}
        return days;
    }
    
    
    public static List<Map<String,Object>> getPastDatesTimestamp(int past) {
    	List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
    	SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
         
        past = past - 1;
        for (int i = past; i >= 0; i--) {
        	Calendar calendar = Calendar.getInstance();
        	calendar.set(Calendar.DAY_OF_YEAR, calendar.get(Calendar.DAY_OF_YEAR) - i);
        	String day = format.format(calendar.getTime());
        	Map<String,Object> map = new HashMap<String,Object>();
        	map.put("day", day);
            map.put("xstime", Date2TimeStamp(day + " 00:00:00", "yyyy-MM-dd HH:mm:ss"));
            map.put("xetime", Date2TimeStamp(day + " 23:59:59", "yyyy-MM-dd HH:mm:ss"));
            list.add(map);
		}
        return list;
    }
    
    
    /**
     * 判断当前日期是星期几
     * 
     * @param pTime 修要判断的时间
     * @return dayForWeek 判断结果
     * @Exception 发生异常
     */
	public static int dayForWeek(String pTime) throws Exception {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		Calendar c = Calendar.getInstance();
		c.setTime(format.parse(pTime));
		int dayForWeek = 0;
		if (c.get(Calendar.DAY_OF_WEEK) == 1) {
			dayForWeek = 7;
		} else {
			dayForWeek = c.get(Calendar.DAY_OF_WEEK) - 1;
		}
		return dayForWeek;
	}
 
	 public static void main(String[] args) throws Exception {
		System.out.println(dayForWeek("2018-03-12 00:00:00"));
	 }
}











